package com.itdata.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.itdata.dao.HibernateDao;

public class HibernateDaoImpl extends HibernateDaoSupport implements
		HibernateDao {

	public void add(Object entity) throws Exception {
		this.getHibernateTemplate().save(entity);
	}

	public void update(Object entity) throws Exception {
		this.getHibernateTemplate().update(entity);
	}

	public void delete(Integer id, Class<?> clz) throws Exception {
		Object o = this.getObjectByID(id, clz);
		if (null != o) {
			this.getHibernateTemplate().delete(o);
		}
	}

	public Object getObjectByID(Integer id, Class<?> clz) throws Exception {
		List<?> list = this.getHibernateTemplate().find(
				"select o from " + clz.getName() + " o where o.id = '" + id
						+ "'");
		return list.size() == 0 ? null : list.get(0);
	}

	public int getCount(String hsql) throws Exception {
		return this.getHibernateTemplate().find(hsql).size();
	}

	public List<?> getObjectList(String hsql, int pageIndex, int pageSize)
			throws Exception {
		Query query = this.getSession().createQuery(hsql);
		query.setFirstResult(pageIndex * pageSize);
		query.setMaxResults(pageSize);
		return query.list();
	}

	public List<?> getAll(String hsql) throws Exception {
		Query query = this.getSession().createQuery(hsql);
		return query.list();
	}

	public void executeNativeSql(final String sql) throws Exception {
		this.getSession().createSQLQuery(sql).executeUpdate();
	}

	public Session getHibernateSession() throws Exception {
		return this.getSession();
	}

	
	public int countByFindHql(String findHql) throws Exception {
		int fromIndex = findHql.toUpperCase().indexOf(" FROM ");
		
		String countHql = "select count(*) ";
		if(fromIndex != -1){
			countHql += findHql.substring(fromIndex);
		} else {
			countHql += findHql;
		}
		
		return count(countHql);
	}
	
	public int count(String countHql)throws Exception{
		Query query = getHibernateSession().createQuery(countHql);
		return Integer.parseInt(query.uniqueResult().toString());
	}
}
